const api = getApp().globalData.api
Page({
    data: {
        get: 0,
        diff: 0,
        result: {},
        show: false,
        outRecord: [],  //出库记录
        actions: [
            {
                name: '删除',
                subname: '该操作是不可逆的，是否确认？',
            },
        ],
    },
    detail: async function (id) {
        let res = await api.curlPost('?cla=outStock&fun=detail', {id: id})
        if (res.code === 1) {
            this.setData({result: res.data.result, outRecord: []})
            this.countTotal(res.data.result.detail)
        } else {
            api.showToast(res.warn)
            wx.navigateBack({delta: 1})
        }
    },
    onLoad: async function (options) {
        const id = options.id ? options.id : ''
        if (!id) {
            api.showToast('参数错误')
            wx.navigateTo({
                url: 'index'
            })
        } else {
            this.detail(id)
        }
    },
    // 刷新入库数据
    onShow: async function () {
      const that = this
      const outData = wx.getStorageSync('outData')
      
      if(outData.id){
        let currentRecord = that.data.outRecord
        if(outData.key){
          currentRecord[outData.key] = outData
        }else{
          currentRecord.push(outData)
        }
        // 当前总出库数量
        let outNum = 0
        for(var index in currentRecord){
          if (currentRecord[index].id === outData.id) {
            outNum += currentRecord[index].outNum
          }
        }
        currentRecord[index].num = outNum
        // let currentLog = that.data.result.outRecord
        // currentLog.push(outData)
        // 遍历数组找到对应的用户 
        let detail = this.data.result.detail.map(mx => {  
          if (mx.id === outData.id) {
            // 如果找到物料则更新数量
            mx.num = Number(outNum);  
          }
          return mx;  
        });  
        let detailtodo = 'result.detail';
        // let inLogtodo = 'result.outRecord';
        that.setData({
            [detailtodo]: detail,
            // [inLogtodo]: currentLog,
            outRecord: currentRecord
        })
        wx.removeStorageSync('outData')
        this.countTotal(that.data.result.detail)
      }
    },
    goto: function (obj) {
        return api.goto(obj)
    },
    countTotal: function (array) {
      let orderNum = api.total(array, 'orderNum')
      let num = api.total(array, 'num')
      let diff = Number(num) - Number(orderNum)
      this.setData({
        get: num,
        diff: diff
      })
    },
    // 提交
    onDone: async function (obj) {
      let that = this
      let data = obj.currentTarget.dataset
      if (!data.id) {
          api.showToast('参数错误')
      } else {
          let res = await api.curlPost(
            '?cla=outStock&fun=done',
             {
               id: data.id,
               outRecord: JSON.stringify(that.data.outRecord),
            }
          )
          if (res.code !== 1) {
              api.showToast(res.warn)
          } else {
              api.showToast('出库完成')
              wx.removeStorageSync('outStockData')
              setTimeout(function () {
                that.detail(data.id)
              }, 1000)
          }
      }
    },
    onPass() {
        api.showToast('执行通过操作')
    },
    onScan: async function (e) {
      let that = this
      wx.scanCode({
          onlyFromCamera: true,
          success(res) {
              if (res.errMsg === "scanCode:ok") {
                  const string = res.result
                  let array = api.parseStr(string)
                  // 扫描物料码
                  if(string.indexOf("=") === -1){
                    array = {barcode: string}
                  }
                  // 通过箱码，匹配入库数据
                  that.caseOutCheck(array)
              }
          }
      })
  },
  caseOutCheck: async function (array) {
    let that = this
    array['id'] = that.data.result.info.id
    let res = await api.curlPost('?cla=outStock&fun=caseOutCheck', array)
      if (res.code !== 1) {
          api.showToast(res.warn)
      } else {
        // 跳转确认出库
        setTimeout(function () {
          wx.navigateTo({
              url: 'out?data=' + JSON.stringify(res.data)
          })
        }, 1000)
      }
  },
  // 删除
  delMaterial(obj) {
    let index = obj.currentTarget.dataset.index,
        id = obj.currentTarget.dataset.id
    let outStockData = this.data.outRecord
    outStockData.splice(index, 1);
    // 当前总入库数量
    let outNum = 0
    for(var key in outStockData){
      if (outStockData[key].id === id) {
        outNum += outStockData[key].outNum
      }
    }
    // 遍历数组找到对应的用户  
    let detail = this.data.result.detail.map(mx => {  
      if (mx.id === id) {
        // 如果找到物料则更新数量
        mx.num = Number(outNum);  
      }
      return mx;  
    });  
    let detailtodo = 'result.detail';
    this.setData({
        [detailtodo]: detail,
        outRecord: outStockData
    })
  }
});